using hao_Model;
using hao_Dto;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using hao_Dto.Product;
using hao_Reppsitory.Product;

namespace Product.Service
{
    public class CategoryService : ICategoryService
    {
        private readonly ICategoryRepository _categoryRepository;
        public CategoryService(ICategoryRepository categoryRepository)
        {
            _categoryRepository = categoryRepository;
        }

        public async Task<List<CategoryDto>> GetCategoryTreeAsync()
        {
            var all = (await _categoryRepository.GetAllAsync()).ToList();
            return BuildTree(all, null);
        }

        private List<CategoryDto> BuildTree(List<Category> all, string parentId)
        {
            return all.Where(c => c.ParentId == parentId || (parentId == null && string.IsNullOrEmpty(c.ParentId)))
                      .OrderBy(c => c.Sort)
                      .Select(c => new CategoryDto
                      {
                          Id = c.Id,
                          Name = c.Name,
                          Children = BuildTree(all, c.Id)
                      }).ToList();
        }
    }
} 